import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';

import { environment } from '../../../environments/environment';

const BASE_URL = environment.baseUrl;

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(
    private http: HttpClient,
    private router: Router,
    private jwtHelper: JwtHelperService
    ) { }

  login(username: string, password: string): Observable<boolean> {
    return this.http.post<{token: string}>( BASE_URL + '/auth', {username: username, password: password})
      .pipe(
        map(result => {
          localStorage.setItem('access_token', result.token);
          return true;
        })
      );
  }

  logout() {
    localStorage.removeItem('access_token');
    this.router.navigate(['login']);
  }

  async loggedIn() {
    // 以token校验结果为登录状态
    const token = localStorage.getItem('access_token');
    // 0.无token
    if (!token) {
      return false;
    }

    // 1.token过期
    if (this.jwtHelper.isTokenExpired()) {
      return false;
    } else {
      // 2.token解密

      const res = await this.http.post<{status: number}>( BASE_URL + '/verify', {token: token}).toPromise();

      if (res.status === 1) {
        return true;
      } else {
        return false;
      }
    }
  }

  getRole(): string {
    const token = this.jwtHelper.decodeToken();
    if (token && token.role) {
      return token.role;
    }
    return null;
  }

}
